<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="department-box box-card">
        <DeptOptions :row="company" :is-root="true" @click-add="onClickAdd" />
        <!-- is-root 以短横线传值，可以以驼峰isRoot接收-->
        <el-tree :data="depts" :props="defaultProps" :default-expand-all="true">
          <template v-slot="scope">
            <DeptOptions :row="scope.data" @onDel="loadDepartments" @click-add="onClickAdd" @click-deit="onClickEdit" />
          </template>
        </el-tree>
      </el-card>
    </div>
    <AddDept ref="addDept" :show-dialog.sync="dialogVisible" :row="deptRow" @add-success="loadDepartments" />
  </div>
</template>

<script>
import { getDepartments } from '@/api/departments.js'
import { transListToTree } from '@/utils'
import AddDept from './components/dept-add'
import DeptOptions from './components/dept-options'
export default {
  name: 'Departments',
  components: {
    DeptOptions,
    AddDept
  },

  data() {
    return {
      defaultProps: {
        label: 'name'

      },
      depts: [],
      company: {},
      dialogVisible: false,
      deptRow: {}

    }
  },
  created() {
    this.loadDepartments()
  },

  methods: {
    async loadDepartments() {
      const res = await getDepartments()
      this.depts = transListToTree('', res.depts)
      this.company = { name: res.companyName, manager: '负责人', children: transListToTree('', res.depts) }
    },
    onClickAdd(data) {
      this.deptRow = data
      this.dialogVisible = true
    },
    onClickEdit(data) {
      this.deptRow = data
      this.dialogVisible = true
      setTimeout(() => {
        this.$refs.addDept.setForm()
      })
    }
  }
}
</script>

<style scoped lang='scss' >

.el-tree{
    margin-top: 10px;
    border-top: 1px solid #ccc
  }

</style>
